<script lang="ts">
import type { FuKuanFangShiXiangQing } from '~/api/services/main.api';

export interface FiatResultProps {
  method?: FuKuanFangShiXiangQing;
  orderNo?: string;
  createTime?: number;
  expireDate?: ReturnType<typeof dayjs>;
  amount?: string;
  currency?: string;
  onContinue?: () => void;
  onClose?: () => void;
};

export const fiatResultPopup = useAntdModal({
  // eslint-disable-next-line import/no-self-import
  is: defineAsyncComponent(() => import('./FiatResult.vue')),
  type: 'body',
}, {
  title: computed(() => $t('mLarXRi6s_3fpesdnMWcn')),
  wrapClassName: 'ant-cover__Modal-drawer',
  centered: true,
  width: 450,
  footer: null,
  keyboard: false,
  maskClosable: false,
});
</script>

<script setup lang="ts">
const props = defineProps<FiatResultProps>();

const appStore = useAppStore();

const getOrderNoRef = computed(() => props.orderNo || '');

const getPaymentMethodInfoRef = computed(() => {
  const data = props.method;
  if (!data)
    return null;
  return {
    img: data.image_icon ? appStore.joinCdnPath(data.image_icon) : '',
    text: data.name,
  };
});

async function getPayResult() {
  if (!getOrderNoRef.value)
    return void 0;

  const res: any = await apis.apiFundDepositQuery(
    { order_no: getOrderNoRef.value },
    { errorMessage: false, checkCode: false, resultType: 'axios' },
  );
  const resData = res?.data;
  if (resData?.code === 0) {
    const data = resData?.data;
    if (data && [1, 2, 5].includes(data?.status)) {
      enabledRef.value = false;
      if (data?.status === 5) {
        onCountDownFinish();
        return data;
      }
      if (data?.status === 1) {
        useCurrencyStore().balanceQry.refetch();
      }
      fiatResultPopup.close();
      globalPopups.wallet.close();
      router.push({ name: RN.PAY_RESULT, query: { status: data?.status === 1 ? 'success' : 'failed', order_no: data.order_no } });
    }
    return data;
  }
  if (resData?.code === 17025) {
    onCountDownFinish();
    return { status: 2 };
  }
  return void 0;
}

const isCountDownFinish = ref(false);

function onCountDownFinish() {
  isCountDownFinish.value = true;
  fiatResultPopup.close();
  globalPopups.wallet.close();
  const query = {
    status: 'failed',
    order_no: getOrderNoRef.value,
    create_time: props.createTime,
    amount: props.amount,
    currency: props.currency,
  };
  getOrderNoRef.value && router.push({ name: RN.PAY_RESULT, query });
}

const enabledRef = ref(false);

useQuery({
  enabled: enabledRef,
  queryKey: [apis.apiFundDepositQuery.id, getOrderNoRef],
  queryFn: getPayResult,
  refetchInterval: ({ state: { data } }) => [1, 2, 5].includes(data?.status) ? false : 3000,
});

watch(getOrderNoRef, (v) => {
  if (v && fiatResultPopup.modalProps?.open) {
    enabledRef.value = true;
  }
  else {
    enabledRef.value = false;
  }
}, { immediate: true });

const router = useRouter();

function toPage() {
  props.onClose?.();
  globalPopups.wallet.close();
  const query = {
    status: 'pending',
    order_no: getOrderNoRef.value,
    create_time: props.createTime,
    amount: props.amount,
    currency: props.currency,
  };
  router.push({ name: RN.PAY_RESULT, query });
}

function continueFn() {
  if (isCountDownFinish.value) {
    return;
  }
  props.onContinue?.();
}
</script>

<template>
  <div>
    <div class="flex-center">
      <i class="i-local:deposit-result-icon !h-12.5 !w-12.5 !text-12.5" />
    </div>
    <div class="grid grid-cols-[auto_1fr] mt-5 gap-2 text-sm text-sys-text-body">
      <div>{{ $t('bxAoUqd3BVdCmlHdpkPj') }}</div>
      <div class="whitespace-normal break-words break-all text-right text-sys-text-head">
        {{ getPaymentMethodInfoRef?.text || '-' }}
      </div>

      <div>{{ $t('wo9Lgc1igeGepW9Bi6O24') }}</div>
      <div class="w-full flex items-center justify-end gap-2 whitespace-normal break-words break-all text-sys-text-head">
        <div class="break-all text-right">
          {{ getOrderNoRef || '-' }}
        </div>
        <TCopy v-if="getOrderNoRef" :source="getOrderNoRef" :nthParent="1" />
      </div>

      <div>{{ $t('h1LpFaGdGy3mt3ciK1O') }}</div>
      <div class="text-right text-sys-text-head">
        {{ createTime ? $d(createTime, 'full') : '-' }}
      </div>

      <div>{{ $t('y3QpPi2X2FeOcmSmCrvZj') }}</div>
      <div class="text-right text-sys-text-head">
        <AStatisticCountdown
          v-if="expireDate"
          class="ant-cover__StatisticCountdown-inline-inherit"
          format="HH:mm:ss"
          :value="expireDate"
          @finish="onCountDownFinish"
        />
        <span v-else>-</span>
      </div>

      <div>{{ $t('wterimikAous8euLqilue') }}</div>
      <div v-if="amount" class="text-right text-green">
        {{ `${amount ?? ''} ${currency ?? ''}`.trim() }}
      </div>
      <span v-else class="text-right text-sys-text-head">-</span>
    </div>

    <div class="grid grid-cols-2 my-5 gap-3 lt-mobile:grid-cols-1">
      <AButton
        class="ant-cover__Button-3d-primary w-full !h-fit !truncate"
        type="primary"
        @click="toPage"
      >
        {{ $t('iQcTEe7VNdG2Uqpnr6gAr') }}
      </AButton>

      <AButton
        class="ant-cover__Button-3d-gray w-full !h-fit !truncate"
        type="primary"
        @click="continueFn"
      >
        {{ isCountDownFinish ? $t('qgN0Bh_8F9bgQtfVqi2d0') : $t('iIzG4GffvgS25Ak7mFv2k') }}
      </AButton>
    </div>
  </div>
</template>
